package com.qujia.station.controller;


import com.alibaba.fastjson.JSONObject;
import com.qujia.common.core.domain.entity.SysDictData;
import com.qujia.common.core.domain.entity.SysUser;
import com.qujia.common.core.domain.model.LoginUser;
import com.qujia.common.exception.CustomException;
import com.qujia.common.utils.SecurityUtils;
import com.qujia.common.utils.StringUtils;
import com.qujia.label.domain.CustomerLabel;
import com.qujia.label.service.ICustomerLabelService;
import com.qujia.label.service.ILabelRuleService;
import com.qujia.station.domain.BusinessAudit;
import com.qujia.station.service.BusinessAuditService;
import com.qujia.system.mapper.SysDictDataMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

/**
 * (BusinessAudit)表控制层
 *
 * @author makejava
 * @since 2023-12-19 16:26:28
 */
@RestController
@RequestMapping("businessAudit")
@Api(tags = "审核")
public class BusinessAuditController {
    /**
     * 服务对象
     */
    @Resource
    private BusinessAuditService businessAuditService;

    @Resource
    private ILabelRuleService labelRuleService;

    @Resource
    private ICustomerLabelService customerLabelService;

    @Resource
    private SysDictDataMapper sysDictDataMapper;

    private static final List<String> auditStatus = new ArrayList<>();
    static {
        auditStatus.add("IN_REVIEW");
        auditStatus.add("PASS");
        auditStatus.add("FAIL");
    }

    /**
     * 分页查询
     *
     * @return 查询结果
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @PostMapping("/queryByPage")
    public ResponseEntity<Page<BusinessAudit>> queryByPage(@RequestBody String json) {
        LoginUser currentUser = SecurityUtils.getLoginUser();



        JSONObject param = JSONObject.parseObject(json);
        BusinessAudit businessAudit = JSONObject.parseObject(json,BusinessAudit.class);
        businessAudit.setEnterpriseId(currentUser.getUser().getEnterpriseId());
        PageRequest pageRequest = PageRequest.of(param.getInteger("page")-1,param.getInteger("size"));
        return ResponseEntity.ok(this.businessAuditService.queryByPage(businessAudit, pageRequest));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    @ApiOperation(value = "通过主键查询单条数据", notes = "通过主键查询单条数据")
    public ResponseEntity<BusinessAudit> queryById(@PathVariable("id") Long id) {
        return ResponseEntity.ok(this.businessAuditService.queryById(id));
    }

    /**
     * 新增数据
     *
     * @param businessAudit 实体
     * @return 新增结果
     */
    @PostMapping
    public ResponseEntity<BusinessAudit> add(@RequestBody BusinessAudit businessAudit) {
        if(StringUtils.isEmpty(businessAudit.getBusinessName())){
            throw new CustomException("businessName不能为空");
        }
        return ResponseEntity.ok(this.businessAuditService.insert(businessAudit));
    }

    /**
     * 编辑数据
     *
     * @param businessAudit 实体
     * @return 编辑结果
     */
    @PutMapping
    public ResponseEntity<BusinessAudit> edit(BusinessAudit businessAudit) {
        return ResponseEntity.ok(this.businessAuditService.update(businessAudit));
    }

    @PostMapping("/audit")
    @ApiOperation(value = "审核", notes = "审核 IN_REVIEW 审核中/PASS 通过/FAIL 审核不通过")
    public ResponseEntity<Map> audit(@RequestBody BusinessAudit audit) {
        Long[] ids = audit.getIds();
        String status = audit.getStatus();
        String auditOpinion = audit.getAuditOpinion();
        if(ids==null||ids.length==0||StringUtils.isEmpty(status)){
            throw new CustomException("ids、status不能为空");
        }
        if(!auditStatus.contains(status)){
            throw new CustomException("不存在的审批状态。IN_REVIEW 审核中/PASS 通过/FAIL 审核不通过");
        }
        int i=0;

        int errCount=0;
        for (Long id : ids) {
            BusinessAudit businessAudit=new BusinessAudit();
            businessAudit.setId(id);
            businessAudit.setStatus(status);
            businessAudit.setAuditTime(new Date());
            businessAudit.setAuditOpinion(auditOpinion);

            BusinessAudit byId = businessAuditService.queryById(id);
            CustomerLabel query = new CustomerLabel();
            query.setPhone(byId.getMobilePhone());
            query.setEnterpriseId(byId.getEnterpriseId());
            query.setLabelId(byId.getBusinessId().intValue());
            query.setDelFlag("0");
            List<CustomerLabel> customerLabelList = customerLabelService.selectCustomerLabelList(query);
            if(customerLabelList.size()>0&&status.equals("PASS")){
                /*Map<String,Object> result=new HashMap<>();
                result.put("code",500);
                result.put("msg","该手机号已经加入渠道");
                return ResponseEntity.ok(result);*/
                errCount++;
                continue;
            }

            BusinessAudit update = businessAuditService.update(businessAudit);
            if(status.equals("PASS")){
                CustomerLabel customerLabel = new CustomerLabel();
                customerLabel.setEnterpriseId(update.getEnterpriseId());
                customerLabel.setLabelId(update.getBusinessId().intValue());
                customerLabel.setPhone(update.getMobilePhone());
                customerLabel.setStationId(update.getStationId());
                LoginUser loginUser= SecurityUtils.getLoginUser();
                customerLabel.setCreateBy(loginUser.getUser().getUserId()+"");
                customerLabel.setCreateTime(new Date());



                customerLabelService.insertCustomerLabel(customerLabel);
            }
            i++;
        }
        Map<String,Object> result=new HashMap<>();
        if(errCount==0){
            result.put("code",200);
            result.put("msg","success");
        }else{
            result.put("code",500);
            result.put("msg","本次审批通过"+i+"位用户，"+errCount+"位已加入渠道审批不通过");
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 删除数据
     *

     * @return 删除是否成功
     */
/*    @DeleteMapping
    public ResponseEntity<Boolean> deleteById(Long id) {
        return ResponseEntity.ok(this.businessAuditService.deleteById(id));
    }*/
    @ExceptionHandler(CustomException.class)
    public ResponseEntity<String> handleUserNotFoundException(CustomException ex) {
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ex.getMessage());
    }

    @GetMapping("/queryLabelRuleType")
    public ResponseEntity<Map> queryLabelRuleType(){


        List<SysDictData> label_rule_type = sysDictDataMapper.selectDictDataByType("label_rule_type");
        Map<String,Object> m=new HashMap<>();
        m.put("code",200);
        m.put("result",label_rule_type);
        m.put("msg","success");
        return ResponseEntity.ok(m);
    }
}

